#coding=utf-8
from stutils import *
set_django_environ()
from stdj.stock.models import *

def is_hengpan(e, n=10, t=[7, 14]):
    '''判断从今天以前n交易日到今天(包括今天),该股票是否处于横盘整理状态.'''
    ps = e.prenday_ps(n)
    if not ps:return False
    
    ps.insert(0, e.price)
    
    #指标1
    end = ps[0].end
    start = ps[-1].end
    change = float( (end-start)*100/end ) 
    change = abs(change)
    
    #指标2
    h = max( [p.high for p in ps] )
    l = min( [p.low for p in ps] )
    avg = sum( [p.end for p in ps] )/ len(ps)
    
    f = float( (h-l)*100/avg )
    
    #print change, f
    x,y = t
    if change < x and f < y:
        return True
    return False
    
tb_hengpan = '''
create table if not exists hengpan
(id integer primary key,
 date text not null,
 code text not null,
 name text not null) 
'''

def hp2db(con, exdate):
    ''''''
    r = []
    for s in Share.objects.order_by('code'):
        try:
            e = s.exday_set.get(date=exdate)
        except Exday.DoesNotExist:
            continue
        
        if is_hengpan(e):
            r.append(s)
    #to db
    c = con.cursor()        
    for s in r:
        print s
        c.execute('''insert into hengpan (date, code, name)
                     values(?,?,?)''',
                     (exdate, s.code, s.name)) 
    con.commit()

def get_hp(con, exdate):
    c = con.cursor()
    c.execute('select code from hengpan where date=?', (exdate,))
    r = c.fetchall()
    
    if not r:return None
    return [i[0] for i in r]

if __name__ == '__main__':
    from stratedy import get_con
    import datetime
    td = datetime.date.today().isoformat()
    
    con = get_con()
    hp2db(con, td)